package com.robinhood.os_spark.animation;


import com.robinhood.os_spark.SparkView;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.render.Path;
import ohos.agp.render.PathMeasure;

/**
 * Animates the sparkline by path-tracing from the first point to the last.
 */
public class LineSparkAnimator extends Animator implements SparkAnimator {

    private final AnimatorValue animator;

    public LineSparkAnimator() {
        animator = new AnimatorValue();
    }

    @Override
    public Animator getAnimation(SparkView sparkView) {
        final Path linePath = sparkView.getSparkLinePath();
        // get path length
        final PathMeasure pathMeasure = new PathMeasure(linePath, false);
        final float endLength = pathMeasure.getLength();

        if (endLength <= 0) {
            return null;
        }
        animator.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float v) {
                float animatedPathLength = v * endLength;
                linePath.reset();
                pathMeasure.getSegment(0, animatedPathLength, linePath, true);
                // set the updated path for the animation
                sparkView.setAnimationPath(linePath);
            }
        });


        return animator;
    }

    @Override
    public long getDelay() {
        return animator.getDelay();
    }

    @Override
    public void setDelayInternal(long startDelay) {
        animator.setDelay(startDelay);
    }

    @Override
    public void setDurationInternal(long duration) {
        animator.setDuration(duration);
    }

    @Override
    public long getDuration() {
        return animator.getDuration();
    }

    @Override
    public void setCurveTypeInternal(int curveType) {
        animator.setCurveType(curveType);
    }


    @Override
    public boolean isRunning() {
        return animator.isRunning();
    }

}
